package com.wwt.friend;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class StepOne {
    public static class MyMapper1 extends Mapper<LongWritable, Text,Text,Text> {
        @Override
        protected void map(LongWritable key, Text value, Mapper<LongWritable,Text,Text,Text>.Context context) throws IOException, InterruptedException {
            String line=value.toString();
            String[] person_friends=line.split(":");
            String person=person_friends[0];
            String[] friends=person_friends[1].split(",");
            for (String friend:friends){
                context.write(new Text(friend),new Text(person));
            }
        }
    }

    public static class MyReduce1 extends Reducer<Text,Text,Text,Text> {
        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            StringBuffer bf= new StringBuffer();
            for (Text friend:values){
                bf.append(friend.toString()).append(",");
            }
            bf=bf.deleteCharAt(bf.length()-1);
            context.write(key,new Text(String.valueOf(bf)));
        }
    }
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);
        job.setJarByClass(StepOne.class);

        job.setMapperClass(MyMapper1.class);
        job.setReducerClass(MyReduce1.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        FileInputFormat.setInputPaths(job,new Path(args[0]));
        Path path2 = new Path(args[1]);
        FileSystem fs = path2.getFileSystem(conf);
        if(fs.exists(path2)){
            fs.delete(path2, true);
        }
        FileOutputFormat.setOutputPath(job,path2);
        System.exit( job.waitForCompletion(true)?0:1);
    }
}
